import React from 'react'
import _, { isString, isArray } from 'lodash'
import moment from 'moment'
import { Select } from 'antd'

const { Option } = Select

/**
 * 动态引入文件夹下多个文件
 * @context {Context} Webpack Require Context
 * @normalize {Function} 把context的key转换为想要的格式,返回falsy值则表示忽略该文件
 * @return {Object} 包含多个文件的引用的对象
 */
export const requireAll = (
    context,
    normalize = v => v.replace(/\.\/([\w./]+)\.\w+$/, '$1').replace(/\//g, '.'),
) => context.keys().reduce((obj, key) => {
    const normalizedKey = normalize(key)
    return _.has(obj, normalizedKey) ? obj : _.set(obj, normalizedKey, context(key).default || context(key))
}, {})

export const compose = (...fns) => fns.reverse().reduce((prevFn, nextFn) => value => nextFn(prevFn(value)))

/**
 * 转换日期，eg:2016-6-18 20:00
 * @param {Date}
 * @return {String}
 */
export const dfmt = (time, formatString = 'YYYY-MM-DD HH:mm:ss') => (time ? moment(time).format(formatString) : '')

/**
 * 通过对象配置信息渲染下拉选项
 * @param {*} obj
 */
export const renderSelectOptsByObj = obj =>
    Object.entries(obj).map(([k, v]) => <Option key={k} value={k} title={v}>{v}</Option>)

/**
 * 通过数组对象配置信息渲染下拉选项
 * @param {*} arr
 */
export const renderSelectOptsByArr = arr =>
    arr.map(({ name, value, ...otherProps }) => <Option key={value} value={value} title={name} {...otherProps} >{name}</Option>)

/**
 * 通过配置信息渲染下拉组件
 * @param {*} options 下拉选项配置信息
 * @param {*} selectProps 下拉配置
 */
export const renderSelectByCfg = (options, selectProps) => {
    let selectOpts = []
    if (Array.isArray(options)) {
        selectOpts = renderSelectOptsByArr(options)
    } else if (typeof options === 'object') {
        selectOpts = renderSelectOptsByObj(options)
    }
    return <Select {...{ placeholder: '请选择', ...selectProps }}>{selectOpts}</Select>
}

export const getTableColumn = (title, dataIndex, width, render, cls, dataSorter) => {
    const { order, field } = dataSorter || {}
    const sorter = !!dataSorter
    const sortOrder = sorter && field === dataIndex ? order : undefined
    const className = sorter && cls === undefined ? 'col-sort' : cls
    return ({
        title, dataIndex, width, render, sorter, sortOrder, className,
    })
}

export const isEmpty = value => {
    if (value === undefined || value === null) {
        return true
    } else if (isString(value)) {
        return value.trim() === ''
    } else if (isArray(value)) {
        return value.length === 0
    }
    return false
}

export default {
    requireAll,
    compose,
    dfmt,
    renderSelectOptsByObj,
    renderSelectOptsByArr,
    renderSelectByCfg,
}
